<template>
  <div>
    <BasicModal v-bind="$attrs" :helpMessage="'提示1'" @ok="okClick" @register="registerModal">
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { setUserPassword } from '/@/api/thingsborad/customers/customers';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { ref } from 'vue';
  import { message } from 'ant-design-vue';

  // 组件通信
  const emits = defineEmits(['closeModelFlag']);
  //激活令牌
  let activateToken = ref<string>();

  //表格字段
  const schemas: FormSchema[] = [
    {
      field: 'password',
      component: 'Input',
      label: '设置密码',
      componentProps: {
        placeholder: '请输入密码',
      },
    },
    {
      field: 'surePassword',
      component: 'Input',
      label: '确定密码',
      componentProps: {
        placeholder: '请输入密码',
      },
    },
  ];
  // 打开表格时数据初始化
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 模块解析 URL 参数
    

    activateToken.value = getActivateToken(data);
    resetFields();
    setModalProps({
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
  });
  // 表格初始化
  const [registerForm, { validate, resetFields }] = useForm({
    layout: 'vertical',
    schemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  // 保存
  async function okClick() {
    setModalProps({
      loading: true,
    });
    const fromData = await validate();
    if (fromData.password !== fromData.surePassword) {
      message.warning('两次密码不一致');
      return;
    }
    let data: any = {
      params: {
        sendActivationMail: true,
      },
      data: {
        activateToken: activateToken.value,
        password: fromData.password,
      },
    };

    // try {
    await setUserPassword(data);
    setModalProps({
      loading: false,
    });
    emits('closeModelFlag', 'close');
    resetFields();
    closeModal();
    // } catch (error) {}
  }
  // 解析activateToken
  function getActivateToken(url: string) {
    const queryStartIndex = url.indexOf('?') + 1;
    const queryParams = url.slice(queryStartIndex);
    const paramPairs = queryParams.split('&');

    for (const pair of paramPairs) {
      const [key, value] = pair.split('=');
      if (key.toLowerCase() === 'activatetoken') {
        return decodeURIComponent(value);
      }
    }
  }
</script>
